/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_12			*/
/*	File:		MrHash.cpp			*/
/********************************************************/

#include "MrHash.h"

CMrHash::CMrHash()
{
	m_ulHash = 0;
}

CMrHash::~CMrHash()
{
}

void CMrHash::MrHashDelete()
{
	CMrShm::MrIpcDelete();

	return;
}

int CMrHash::MrHashCreate(key_t iKey, ULONG ulHash)
{
	int iReturn = MR_SUCCESS;

	if (MR_SUCCESS == CMrShm::MrIpcCreate(iKey, ulHash * sizeof(void*))) {
		CMrShm::MrShmReset(ulHash * sizeof(void*));
		m_ulHash = ulHash;
	}
	else {
		iReturn = MR_FAILURE;
	}

	return iReturn;
}

ULONGLONG CMrHash::MrHashFunction(char* pszKey, UINT uiLength)
{
	UINT uiIndex = 0;
	ULONGLONG ullReturn = 0;

	ullReturn = MR_BASIC * uiLength;
	for (; uiIndex < uiLength; uiIndex ++) {
		ullReturn = (ullReturn + (*(pszKey + uiIndex) << (uiIndex * 13 % 24))) & MR_MASK;
	}

	ullReturn = (MR_OFFSET * ullReturn + MR_PLUS) & MR_MASK;  

	return ullReturn;
}

void* CMrHash::MrHashGetBucket(ULONGLONG ullKey)
{
	return (void*)((UCHAR*)m_pShm + (sizeof(void*) * (ullKey % m_ulHash)));
}

void CMrHash::MrHashPutBucket(ULONGLONG ullKey, void** ppKey)
{
	void* pBucket = NULL;

	pBucket = MrHashGetBucket(ullKey);
	memcpy(&pBucket, ppKey, sizeof(void*));

	return;
}
